/*
 * 路由配置,更贴合uniapp的写法
 * uni-crazy-router
 * 对h5 production环境打包时的特殊处理，否则uni-crazy-router在这个环境会异常
 * 安装插件：uni-vite-plugin-h5-prod-effect
 */
import uniCrazyRouter, {
  beforeEach,
  afterEach,
  onError,
  afterNotNext,
} from "uni-crazy-router";

import pagesJson from "@/pages.json";
// 判断是否存在分包配置
let pagesList = [];
if (pagesJson.subpackages && pagesJson.subpackages.length) {
  pagesJson.subpackages.forEach((item) => {
    item.pages &&
      item.pages.forEach((it) => {
        pagesList.push({
          name: it.name,
          path: `${item.root}/${it.path}`,
          style: {},
        });
      });
  });
  pagesList = [...pagesJson.pages, ...pagesList];
} else {
  pagesList = pagesJson.pages;
}
function restoreUrl(path, query) {
  let count = 0;
  for (const key in query) {
    path += `${count === 0 ? "?" : "&"}${key}=${query[key]}`;
    count += 1;
  }
  return `/${path}`;
}

export function getPageByName(name) {
  const pages = pagesList;
  const targetPage = pages.find((i) => i.name === name);
  if (!targetPage) return;
  return targetPage;
}

// 回退
export function navigateBack(delta) {
  const pages = getCurrentPages();
  if (pages && pages.length > 1) {
    uni.navigateBack({
      delta,
    });
  } else {
    history.back();
  }
}

// 跳转路由的方式及参数设置
export function navigate(method, name, query = {}, successCallback) {
  const targetPage = getPageByName(name);
  if (!targetPage) return;
  const url = restoreUrl(targetPage.path, query);
  switch (method) {
    case "redirectTo":
      uni.redirectTo({
        url,
        success: (res) => {
          successCallback && successCallback(res);
        },
      });
      return;
    case "switchTab":
      uni.switchTab({
        url,
        success: (res) => {
          successCallback && successCallback(res);
        },
      });
      return;
    case "reLaunch":
      uni.reLaunch({
        url,
        success: (res) => {
          successCallback && successCallback(res);
        },
      });
      return;
    case "navigateTo":
      uni.navigateTo({
        url,
        success: (res) => {
          successCallback && successCallback(res);
        },
      });
      return;
  }
}

// 对路由进行拦截
export function setupRouter(app) {
  // 接收vue3的实例
  app.use(uniCrazyRouter);
  const token = uni.getStorageSync("userInfo").token;

  beforeEach(async (to, from, next) => {
    // 对路由进行白名单设置
    const whiteList = [
      "pages/tabbar/home/index",
      "pages/tabbar/workspace/index",
      "pages/tabbar/setting/index",
      "pages/login/index",
      "pages/system/index",
      "modulePagesB/pages/system/index",
      "modulePagesA/pages/addForm/index",
      "pages/scan/index",
      "pages/map/index",
      "pages/rim/index",
      "pages/infoDetail/index",
      "pages/uploadForm/index",
      "pages/editInfo/index",
      "pages/settingPage/index",
      "pages/editPwd/index",
      "pages/toMsg/index",
      "pages/canvasView/index",
      "pages/pdf/index",
      "/",
    ];

    // 对路由进行鉴权设置
    if (token || whiteList.indexOf(to.url) != -1) {
      next();
    } else {
      afterNotNext(() => {
        uni.showToast({
          title: "登录状态已过期，请重新登录",
          icon: "none",
        });
        navigate("navigateTo", "login");

        // uni.navigateTo({
        // 	url: '/pages/login/index',
        // 	passedParams: {
        // 		info: '因为没有token，拦截跳转到登陆页',
        // 	},
        // })
      });
    }
  });

  afterEach((to, from) => {
    // 逻辑代码
  });

  // 除了在beforeEach钩子里没有使用next导致的无法跳转的情况外，其他情况导致的跳转失败都会触发onError
  onError((to, from) => {
    uni.showToast({
      title: `${to.url} 不存在1111`,
      icon: "none",
    });
  });
}
